package com.jzg.jcptadmin.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.adpter.HistoryAdapter;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.History;
import com.jzg.jcptadmin.data.vo.HistoryList;
import com.jzg.jcptadmin.data.vo.PopListDataModel;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.Style;
import com.jzg.jcptadmin.data.vo.ValuationDetailData;
import com.jzg.jcptadmin.presenter.HistoryPresenter;
import com.jzg.jcptadmin.view.PopWindowView;
import com.jzg.jcptadmin.viewinterface.HistoryActivityInterface;
import com.jzg.template.refreshrecycleview.DividerItemDecoration;
import com.jzg.template.refreshrecycleview.RefreshBaseAdapter;
import com.jzg.template.refreshrecycleview.RefreshRecycleView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangyd on 16/1/7.
 * 估值历史
 */
public class HistoryActivity extends BaseActivity implements HistoryActivityInterface, RefreshRecycleView.OnStateChangeLstener, View.OnClickListener {

    @Bind(R.id.title_content)
    TextView title_content;
    @Bind(R.id.title_return)
    ImageView title_return;

    @Bind(R.id.history_recycler)
    RefreshRecycleView historyRecycler;
    @Bind(R.id.car_manager_pinpai)
    TextView carManagerPinpai;
    @Bind(R.id.car_manager_price)
    TextView carManagerPrice;
    @Bind(R.id.car_manager_area)
    TextView carManagerArea;
    @Bind(R.id.car_manager_status)
    TextView carManagerStatus;
    @Bind(R.id.fast_empty_view)
    ViewStub fastEmptyView;
    @Bind(R.id.fast_hintline)
    View fastHintline;
    private HistoryAdapter historyAdapter;

    private HistoryPresenter historyPresenter;
    //(0默认，1刷新，2加载）
    private int Operation = 0;
    private String MakeId = "";
    private String ModelId = "";
    private String StyleId = "";
    private String C2BPrice = "";
    private String Mileage = "";
    private String RegisterDate = "";
    private String pageId = "0";
    private List<History> mDatas = new ArrayList<>();
    private PopWindowView pop;
    //选择信息广播接收器
    private SelectInfoReceiver selectInfoReceiver;
    private StatusData statusData;//状态

    private int curHistoryPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history_layout);
        ButterKnife.bind(this);
        showDialog();
        historyPresenter = new HistoryPresenter(DataManager.getInstance());
        historyPresenter.attachView(this);
        historyPresenter.loadHistory();
        historyAdapter = new HistoryAdapter(this, mDatas);
        historyRecycler.setAdapter(historyAdapter);
        historyRecycler.setColorSchemeColors(Color.parseColor(Constant.ACTIVITY_REFRESHCOLOR));
        historyRecycler.setOnStateChangeLstener(this);
        historyRecycler.mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        historyRecycler.setLayoutManager(linearLayoutManager);
        title_content.setText(R.string.history_title);
        statusData = appContext.getStatus();
        pop = new PopWindowView(this, carManagerPinpai, carManagerPrice, carManagerArea, carManagerStatus, fastHintline);

        //注册接受车辆选择和城市选择的广播接收器
        selectInfoReceiver = new SelectInfoReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.CAR_SELECT_BROADCAST);
        filter.addAction(Constant.CAR_SELECT_ALL_MAKE_BROADCAST);
        LocalBroadcastManager.getInstance(this).registerReceiver(selectInfoReceiver, filter);

        historyAdapter.setOnItemClickLitener(new RefreshBaseAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                curHistoryPosition = position;
                historyPresenter.loadEstimate();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (historyPresenter == null) {
            historyPresenter.detachView();
        }
        ButterKnife.unbind(this);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(selectInfoReceiver);
    }

    /**
     * 获取历史请求需要的参数
     *
     * @return
     */
    @Override
    public Map<String, String> getHistoryParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("tokenid", "6");
        params.put("operation", Operation + "");
        params.put("userid", appContext.getUser().getUserId() + "");
        params.put("PageId", pageId);
        params.put("MakeId", MakeId);
        params.put("modelId", ModelId);
        params.put("StyleId", StyleId);
        params.put("mileage", Mileage);
        params.put("C2BPrice", C2BPrice);
        params.put("RegisterDate", RegisterDate);
        return params;
    }

    /**
     * 获取查询估值结果参数
     *
     * @return
     */
    @Override
    public Map<String, String> getEstimateParams() {
        Map<String, String> params = new HashMap<>();
        params.put("tokenid", "6");
        params.put("UserId", String.valueOf(appContext.getUser().getUserId()));
        params.put("carId", mDatas.get(curHistoryPosition).getID());
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));
        return params;
    }

    /**
     * 加载估值结果
     */
    @Override
    public void loadValuationDetail(ValuationDetailData valuationDetailData) {
        ActivityHelp.startActivity(HistoryActivity.this, ValuationDetailActivity.class, ActivityHelp.ESTIMATEDETAILS, valuationDetailData);
    }

    /**
     * 显示历史列表
     *
     * @param historyList
     */
    @Override
    public void showHistory(HistoryList historyList) {
        historyRecycler.setRefreshing(false);
        if (historyList.getStatus() == Constant.SUCCESS) {
            if (Operation == 0) {
                showData(historyList);
            } else {
                showMoreHistory(historyList);
            }
        } else {
            Toast.makeText(HistoryActivity.this, historyList.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    private void showData(HistoryList historyList) {
        if (historyList.getAppraiseList().size() == 0) {
            fastEmptyView.setVisibility(View.VISIBLE);
            historyRecycler.setVisibility(View.GONE);
        } else {
            fastEmptyView.setVisibility(View.GONE);
            historyRecycler.setVisibility(View.VISIBLE);
            mDatas.clear();
            mDatas.addAll(historyList.getAppraiseList());
            historyAdapter.update(mDatas);
        }
    }

    @Override
    public void showMoreHistory(HistoryList historyList) {
        if (historyList.getAppraiseList().size() == 0) {
            historyRecycler.setRefreshing(false);
            historyRecycler.setAdapterLastState(RefreshRecycleView.STATE_NO_MORE);
        } else {
            mDatas.addAll(historyList.getAppraiseList());
            historyAdapter.update(mDatas);
            historyRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_LOADEMORE);
        }
    }

    /**
     * 显示错误信息
     *
     * @param error 错误信息
     */
    @Override
    public void showError(String error) {
        try {
            historyRecycler.setRefreshing(false);//停止显示加载动画
            if (error.startsWith("1")) {
                //设置最后一行显示加载失败
                historyRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
            } else {
                Toast.makeText(HistoryActivity.this,Constant.errr_net, Toast.LENGTH_SHORT).show();
                dismissDialog();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        Operation = 0;
        if (appContext.isNetWork && mDatas.size() > 0) {
            historyPresenter.loadHistory();
        } else {
            historyRecycler.setRefreshing(false);//停止显示加载动画
        }
    }

    @Override
    public void onBottom() {
        Operation = 2;
        if (mDatas.size() > 9) {
            pageId = mDatas.get(mDatas.size() - 1).getID();
            if (appContext.isNetWork) {
                historyPresenter.loadHistory();
            } else {
                historyRecycler.setRefreshing(false);//停止显示加载动画
                historyRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
            }
        }

    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */

    @OnClick({R.id.title_return, R.id.car_manager_pinpai, R.id.car_manager_price, R.id.car_manager_area, R.id.car_manager_status})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_return:
                finish();
                break;
            //品牌
            case R.id.car_manager_pinpai:
                ActivityHelp.startActivity(this, BrandActivity.class, Constant.CAR_IS_MAKE_ALL, true);
//                CarStatus =true;

                break;
            //价格
            case R.id.car_manager_price:
                if (statusData != null) {
                    setPopDataByPrice();
                    pop.controlPopWindowShow(carManagerPrice, carManagerPinpai, carManagerArea, carManagerStatus);
                } else {
                    Toast.makeText(HistoryActivity.this, "无筛选数据", Toast.LENGTH_SHORT).show();
                }
                break;
            //里程
            case R.id.car_manager_area:
                if (statusData != null) {
                    setPopDataByMileage();
                    pop.controlPopWindowShow(carManagerArea, carManagerPinpai, carManagerStatus, carManagerPrice);
                } else {
                    Toast.makeText(HistoryActivity.this, "无筛选数据", Toast.LENGTH_SHORT).show();
                }

                break;
            //年限
            case R.id.car_manager_status:
                if (statusData != null) {
                    setPopDataByYear();
                    pop.controlPopWindowShow(carManagerStatus, carManagerPinpai, carManagerArea, carManagerPrice);
                } else {
                    Toast.makeText(HistoryActivity.this, "无筛选数据", Toast.LENGTH_SHORT).show();
                }
                break;
            //上牌年限
            case R.id.fragment_buy_car_my_concern://添加车辆
//                ActivityHelp.startActivity(this, AddCarActivity.class);
                break;
        }
    }

    /**
     * 行驶里程筛选数据
     */
    private void setPopDataByMileage() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();
        for (int i = 0; i < statusData.getItemList().getMileageInfo().getItem().size(); i++) {
            String value = statusData.getItemList().getMileageInfo().getItem().get(i).getValue();
            String valueID = statusData.getItemList().getMileageInfo().getItem().get(i).getId();
            if (i == 0) {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.text_blue));
            } else {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.light_grey_text));
            }

        }
        pop.setData(mSortList);


    }

    /**
     * 上牌年限筛选数据
     */
    private void setPopDataByYear() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();
        for (int i = 0; i < statusData.getItemList().getRegisterInfo().getItem().size(); i++) {
            String value = statusData.getItemList().getRegisterInfo().getItem().get(i).getValue();
            String valueID = statusData.getItemList().getRegisterInfo().getItem().get(i).getId();
            if (i == 0) {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.text_blue));
            } else {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.light_grey_text));
            }

        }
        pop.setData(mSortList);


    }

    /**
     * 价格筛选数据
     */
    private void setPopDataByPrice() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();

        for (int i = 0; i < statusData.getItemList().getPriceInfo().getItem().size(); i++) {
            String value = statusData.getItemList().getPriceInfo().getItem().get(i).getValue();
            String valueID = statusData.getItemList().getPriceInfo().getItem().get(i).getId();
            if (i == 0) {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.text_blue));
            } else {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.light_grey_text));
            }

        }
        pop.setData(mSortList);
    }

    @Override
    public void filter_date(int status1, int position) {
        super.filter_date(status1, position);
        Operation = 0;
        //点击了价格
        if (R.id.car_manager_price == status1) {
            C2BPrice = appContext.getStatus().getItemList().getPriceInfo().getItem().get(position).getId();
            historyPresenter.loadHistory();
        } else if (R.id.car_manager_area == status1) {
            //里程
            Mileage = appContext.getStatus().getItemList().getMileageInfo().getItem().get(position).getId();
            historyPresenter.loadHistory();
        } else if (R.id.car_manager_status == status1) {
            //年限
            RegisterDate = appContext.getStatus().getItemList().getRegisterInfo().getItem().get(position).getId();
            historyPresenter.loadHistory();
        }
    }

    /**
     * 选择品牌、车系、车型、省、市广播接受
     */
    class SelectInfoReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constant.CAR_SELECT_BROADCAST)) {
                Style style = intent.getParcelableExtra(Constant.STYLE);
                MakeId = style.getMakeId() + "";
                ModelId = style.getModelId() + "";
                StyleId = style.getId() + "";
                carManagerPinpai.setText(style.getFullName());
                showDialog();
                Operation = 0;
                historyPresenter.loadHistory();
            } else if (intent.getAction().equals(Constant.CAR_SELECT_ALL_MAKE_BROADCAST)) {
                Logger.i(Constant.CAR_SELECT_ALL_MAKE_BROADCAST);
                MakeId = "";
                ModelId = "";
                StyleId = "";
                carManagerPinpai.setText("全部");
                showDialog();
                historyPresenter.loadHistory();
            }
        }

    }

}
